﻿<%@ WebHandler Language="C#" Class="ZSEntrustMeteringHandler" %>

using System;
using System.Web;
using System.Web.SessionState;
using System.Collections.Generic;
using System.Data;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using Newtonsoft.Json;
using DatabaseAccess.DBUtility;
using BusinessRule.DTO;

/// <summary>
/// 理化试验结果查询
/// </summary>
public class ZSEntrustMeteringHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    private uLMSCommonIBusiness m_CommonObj = uMESBusinessFactory.instance.GetuLMSCommonObject();
    private uLMSEntrustIBusiness m_entrust = uMESBusinessFactory.instance.GetuLMSEntrustMetering();
    private uLMSMfgOrderIBusiness m_MfgOrderObj = uMESBusinessFactory.instance.GetuLMSMfgOrderObject();
    private uLMSContainerIBusiness m_ContainerObj = uMESBusinessFactory.instance.GetuLMSContainerObject();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "GetEntrustMeteringData": //查询理化试验信息
                    GetEntrustMeteringData(context);
                    break;
                case "GetEntrustCheckPointData"://查询理化检测项信息
                    GetEntrustCheckPointData(context);
                    break;
                case"GetContainerNoCheckData"://查询三分厂开卡未检验的批次信息
                    GetContainerNoCheckData(context);
                    break;
                case "GetChildContainerNo"://子卡批次信息
                    GetChildContainerNo(context);
                    break;
                case "GetLHData"://三分厂开卡未检验理化申请
                    GetLHData(context);
                    break;    
                case"DownloadFile":
                    DownloadFile(context);
                    break;    
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
    /// <summary>
    /// 查询理化试验信息
    /// </summary>
    /// <param name="context"></param>
    private void GetEntrustMeteringData(HttpContext context) 
    {
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        int pageSize =Convert.ToInt32(context.Request["pageSize"].ToString());
        int pageNumber = Convert.ToInt32(context.Request["pageNumber"].ToString());
        var result = new uMESProcessResult();
        var selectSQL = @"SELECT m.MFGORDERNAME,e.ENTRUSTMEASUREMENTID,e.ENGINENO,pb.PRODUCTNAME,p.DESCRIPTION PRODUCTDESC,c.containername BATCHNO,f.FACTORYNAME,e.ENTRUSTNAME,e.ENTRUSTQTY,e.ENTRUSTDATE,
                    e.STATUS,e.IQSORDERQMSNOLH,e.FINISHREPORTTIME,e.TESTRESULT,e.SENDEMPLOYEENAME,e.SENDDATE,e.RECVEMPLOYEENAME,e.RECVDATE,e.TREATNOTE,e.QMSENTRUSTNAME,e.reportUrl,em.FULLNAME,'' RESXML,'' SENDXML  
                    FROM EntrustMeasurement e 
                    LEFT JOIN PRODUCT p ON p.PRODUCTID =e.PRODUCTID 
                    LEFT JOIN productbase pb ON pb.productbaseid=p.productbaseid
                    LEFT JOIN container c ON c.containerid=e.containerid
                    LEFT JOIN FACTORY f ON f.FACTORYID =e.FACTORYID
                    LEFT JOIN employee em on em.employeeid =e.EntrustorID 
                    LEFT JOIN MFGORDER m ON m.MFGORDERID =c.MFGORDERID
                    --LEFT JOIN WRITETOOTHERSYSTEM w ON w.PARENTID =e.ENTRUSTMEASUREMENTID                                                         
                    WHERE e.FACTORYID='" + m_UserInfo.FactoryID+"'";
        if (!string.IsNullOrWhiteSpace(argPara["txtContainerNO"])) { selectSQL += " AND c.containername like '%" + argPara["txtContainerNO"] + "%'"; }
        if (!string.IsNullOrWhiteSpace(argPara["txtProductName"])) { selectSQL+=" AND pb.PRODUCTNAME like '%"+argPara["txtProductName"]+"%'"; }
        if (!string.IsNullOrWhiteSpace(argPara["txtProductDesc"])) { selectSQL += " AND p.DESCRIPTION like '%" + argPara["txtProductDesc"] + "%'"; }
        if (!string.IsNullOrWhiteSpace(argPara["txtMfgOrderName"])) { selectSQL += " AND m.MFGORDERNAME like '%" + argPara["txtMfgOrderName"] + "%'"; }
        if (!string.IsNullOrWhiteSpace(argPara["txtEntrustDate"])) { selectSQL+=" AND to_char(e.ENTRUSTDATE,'yyyy-MM-dd')>='"+argPara["txtEntrustDate"]+"'"; }
        selectSQL += " order by e.ENTRUSTDATE desc";
        var paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = pageNumber;
        paraPage.PageSize = pageSize;
        paraPage.strSQL = selectSQL;
        result = DatabaseHelper.RunProcedureForPage(paraPage);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 查询理化试验检测项信息
    /// </summary>
    /// <param name="context"></param>
    private void GetEntrustCheckPointData(HttpContext context)
    {
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var result = new uMESProcessResult();
        var dt = m_entrust.GetEntrustMeteringDetailInfo(argPara["EntrustMeasurementID"]);
        result.DBTable = dt;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 查询三分厂开卡未检验的批次信息
    /// </summary>
    /// <param name="context"></param>
    private void GetContainerNoCheckData(HttpContext context) 
    {
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var pageSize = context.Request["pageSize"].ToString();
        var pageNumber = context.Request["pageNumber"].ToString();
        var para=new Dictionary<string,string>();
            para.Add("PageSize", pageSize);
            para.Add("CurrentPageIndex", pageNumber);
            para.Add("FactoryID", m_UserInfo.FactoryID);
            para.Add("OpenNocheck", "");
            if (!string.IsNullOrWhiteSpace(argPara["mfgOrderName"])) { para.Add("mfgOrderName", argPara["mfgOrderName"]); }
            if (!string.IsNullOrWhiteSpace(argPara["ProductName"])) { para.Add("ProductName", argPara["ProductName"]); }
            if (!string.IsNullOrWhiteSpace(argPara["ContainerName"])) { para.Add("LHContainerName", argPara["ContainerName"]); }
        uMESProcessResult result= m_MfgOrderObj.GetMfgOrderData(para);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 子卡批次信息
    /// </summary>
    /// <param name="context"></param>
    private void GetChildContainerNo(HttpContext context) 
    {
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var ContainerName = context.Request["ContainerName"].ToString();
        uMESProcessResult result = new uMESProcessResult();//m_ContainerObj.GetContainerListByMfgOrder(argPara["MFGORDERID"]);
        var para=new Dictionary<string,string>();
        para.Add("ProductName", argPara["PRODUCTNAME"]);
        para.Add("ProductRev", argPara["PRODUCTREVISION"]);
        para.Add("FactoryID", m_UserInfo.FactoryID);
        var wfdata = m_CommonObj.GetWorkFlowSetpsByWorkflowID(argPara["WORKFLOWID"]); //m_CommonObj.GetWorkflowInfoWithOtherAndSubByProductInfo(para, true, true);
        result.ReturnData = wfdata;
        result.DBTable = GetContainerListByMfgOrder(argPara["MFGORDERID"].ToString(), ContainerName);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private DataTable GetContainerListByMfgOrder(string MFGORDERID,string ContainerName) 
    {
        string sql = @"SELECT C.CONTAINERID,C.CONTAINERNAME,C.QTY,C.CONTAINERTYPE, C.TOGETHERFLAG
            FROM CONTAINER C
            LEFT JOIN containercurrentinfo cci ON cci.containerid =c.containerid
            WHERE  C.PARENTCONTAINERID IS NULL AND C.STATUS = 1 AND cci.isinstore <>1 --AND C.qualificationqty=1
            AND C.MFGORDERID = '{0}' and C.CONTAINERNAME like '%{1}%' ORDER BY C.CONTAINERID";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(string.Format(sql, MFGORDERID, ContainerName));
        return dt;
    }
    
    /// <summary>
    /// 三分厂开卡未检验理化申请
    /// </summary>
    /// <param name="context"></param>
    private void GetLHData(HttpContext context) 
    {
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var dt = new DataTable();
        dt.Columns.Add("ContainerName");
        dt.Columns.Add("ContainerID");
        dt.Columns.Add("WipQty");
        dt.Columns.Add("ProductName");
        dt.Columns.Add("ProductDescription");
        dt.Columns.Add("ProductID");
        dt.Columns.Add("WorkflowStepID");
        dt.Columns.Add("WorkflowStepName");
        dt.Columns.Add("WorkReportNum");
        DataRow row = dt.NewRow();
        row["ContainerName"] = argPara["ContainerName"];
        row["ContainerID"] = argPara["ContainerID"];
        row["WipQty"] = argPara["WipQty"];
        row["ProductName"] = argPara["ProductName"];
        row["ProductDescription"] = argPara["ProductDescription"];
        row["ProductID"] = argPara["ProductID"];
        row["WorkflowStepID"] = argPara["WorkflowStepID"];
        row["WorkflowStepName"] = argPara["WorkflowStepName"];
        row["WorkReportNum"] = argPara["WipQty"];
        dt.Rows.Add(row);
        context.Session["PopupData"] = dt;
        uMESProcessResult result = new uMESProcessResult();
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void DownloadFile(HttpContext context)
    {
        string url = @"http://10.15.5.31:80/prod-api/liyang/ShowReport/mes?entrustName= " + context.Request["entrustName"].ToString() + "&bid=" + context.Request["bid"].ToString();
        //var urll = @"http://39.102.129.205:8080/prod-api/liyang/ShowReport/mes?entrustName=物资供应-20230015&bid=f32945229bc0b1fc";
        string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";//客户端保存的文件名  
        System.Net.WebClient wc = new System.Net.WebClient();
        wc.Encoding = System.Text.Encoding.GetEncoding("gb2312");
        byte[] bytess = wc.DownloadData(url);
        context.Response.Clear();
        //二进制流数据（如常见的文件下载）
        context.Response.ContentType = "application/octet-stream";
        //通知浏览器下载文件而不是打开  
        context.Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
        context.Response.BinaryWrite(bytess);
        context.Response.Flush();
    }
    
}